import React, { useState, useEffect } from 'react'
import { Card, Button, Form, Input, Select, Radio, Modal, DatePicker, Table, message, Pagination } from 'antd'
import {
  EditOutlined,
  FormOutlined,
  HighlightOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import axios from '../../axios/index'
import Utils from '../../utils/utils'

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;

const User = () => {

  const [list, setList] = useState([])
  const [page, setPage] = useState(1)
  const [pagination, setPagination] = useState(1)
  const [selectedItem, setSelectedItem] = useState(null)
  const [visible, setVisible] = useState(false)
  const [title, setTitle] = useState('')
  const [type, setType] = useState('')
  const [userInfo, setUserInfo] = useState(null)

  const onCreate = (values) => {
    console.log('create user', values);
    setVisible(false);
    axios.ajax({
      url: '/user/create',
      data: {
        params: {
          values
        }
      }
    }).then((res) => {
      if (res.status === 200 && res.code === 0) {
        message.info(res.result);
        requestList()
      }
    })
  }

  const handleOperator = (type) => {
    let item = selectedItem
    if (type === 'create') {
      setVisible(true)
      setTitle('创建员工')
      setType(type)
    } else if (type === 'edit' || type === 'detail') {
      if (!item) {
        Modal.info({
          title: '信息',
          content: '请选择一个用户'
        })
        return
      }
      setVisible(true)
      setTitle(type === 'edit' ? '编辑用户' : '查看详情')
      setUserInfo(item)
      setType(type)
    } else if (type === 'delete') {
      if (!item) {
        Modal.info({
          title: '信息',
          content: '请选择一个用户'
        })
        return
      }
      Modal.confirm({
        title: '确认删除',
        content: '是否删除当前选中数据',
        onOk() {
          axios.ajax({
            url: '/user/delete',
            data: {
              params: {
                id: item[0].id
              }
            }
          }).then((res) => {
            if (res.status === 200 && res.code === 0) {
              message.info(res.result);
              requestList()
              setVisible(false)
            }
          })
        }
      })
    }
  }

  const columns = [{
    title: 'id',
    dataIndex: 'id'
  }, {
    title: '用户名',
    dataIndex: 'username'
  }, {
    title: '性别',
    dataIndex: 'sex',
    render(sex) {
      return sex === 1 ? '男' : '女'
    }
  }, {
    title: '职位',
    dataIndex: 'state',
    render(state) {
      let config = {
        '1': '销售部经理',
        '2': '市场部副经理',
        '3': '研发部部长',
        '4': '测试组副组长',
        '5': '人事部副部长'
      }
      return config[state];
    }
  }, {
    title: '爱好',
    dataIndex: 'interest',
  }, {
    title: '婚姻',
    dataIndex: 'isMarried',
    render(isMarried) {
      return isMarried ? '已婚' : '未婚'
    }
  }, {
    title: '生日',
    dataIndex: 'birthday',
    render: Utils.formateDate
  }, {
    title: '联系地址',
    dataIndex: 'address'
  }, {
    title: '创建时间',
    dataIndex: 'time',
    render: Utils.formateDate
  }]

  const requestList = (pagination) => {
    axios.ajax({
      url: '/user/list',
      data: {
        params: {
          page: pagination
        }
      }
    }).then((res) => {
      let list = res.result.list.map((item, index) => {
        item.key = index;
        return item;
      });
      setList(list)
    })
  }

  useEffect(() => {
    requestList(pagination)
  }, [pagination])

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedItem(selectedRows)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      name: record.name,
    }),
  };

  const paginationChange = (pagination) => {
    setPagination(pagination)
  }

  return (
    <div style={{ width: '100%' }}>
      <Card style={{ paddingTop: 20 }}>
        <Form layout="inline">
          <FormItem>
            <Input placeholder="请输入用户名" />
          </FormItem>
          <FormItem>
            <DatePicker placeholder="请选择入职日期" />
          </FormItem>
          <FormItem>
            <Input placeholder="用户手机号" />
          </FormItem>
          <FormItem>
            <Button type="primary">查询</Button>
          </FormItem>
        </Form>
      </Card>
      <Card style={{ marginTop: 10, paddingTop: 20 }}>
        <Button type="primary" icon={<FormOutlined />} onClick={() => handleOperator('create')}>创建员工</Button>
        <Button icon={<HighlightOutlined />} onClick={() => handleOperator('detail')}>员工详情</Button>
        <Button type="danger" icon={<DeleteOutlined />} onClick={() => handleOperator('delete')}>删除员工</Button>
      </Card>
      <div className="content-wrap">
        <Card>
          <Table
            columns={columns}
            rowSelection={{
              type: 'radio',
              ...rowSelection,
            }}
            dataSource={list}
            pagination={false}
          />
          <div className="pagination" style={{ float: 'right', marginTop: 20 }}>
            <Pagination onChange={paginationChange} defaultCurrent={1} total={10 * (pagination + 1)} />
          </div>
        </Card>
        <UserForm
          visible={visible}
          onCreate={onCreate}
          onCancel={() => {
            setVisible(false);
          }}
          userInfo={userInfo}
          type={type}
        />
      </div>
    </div>
  )
}

const UserForm = ({ visible, onCreate, onCancel, userInfo, type }) => {
  const [form] = Form.useForm()

  const getState = (state) => {
    return {
      '1': '销售部经理',
      '2': '市场部副经理',
      '3': '研发部部长',
      '4': '测试组副组长',
      '5': '人事部副部长'
    }[state]
  }

  let footer = {}
  if (type === 'detail') {
    footer = {
      footer: null
    }
  }
  return (
    <Modal
      visible={visible}
      title="开通城市"
      okText="确认"
      cancelText="取消"
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields();
            onCreate(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
      {...footer}
    >
      <Form
        form={form}
        layout="horizontal"
        name="form_in_modal"
        initialValues={{
          modifier: 'public',
        }}
      >
        <Form.Item name="username" label="姓名">
          {
            userInfo && type === 'detail' ? userInfo[0].username :
              <Input type="text" placeholder="请输入姓名" />
          }
        </Form.Item>
        <Form.Item name="sex" label="性别">
          {
            userInfo && type === 'detail' ? userInfo[0].sex === 1 ? '男' : '女' :
              <RadioGroup>
                <Radio value={1}>男</Radio>
                <Radio value={2}>女</Radio>
              </RadioGroup>
          }
        </Form.Item>
        <Form.Item name="isMarried" label="婚姻">
          {
            userInfo && type === 'detail' ? userInfo[0].isMarried === 1 ? '已婚' : '未婚' :
              <RadioGroup>
                <Radio value={1}>已婚</Radio>
                <Radio value={2}>未婚</Radio>
              </RadioGroup>
          }
        </Form.Item>
        <Form.Item name="state" label="职位">
          {
            userInfo && type === 'detail' ? getState(userInfo[0].state) :
              <Select>
                <Option value={1}>咸鱼一条</Option>
                <Option value={2}>风华浪子</Option>
                <Option value={3}>北大才子一枚</Option>
                <Option value={4}>百度FE</Option>
                <Option value={5}>创业者</Option>
              </Select>
          }
        </Form.Item>
        <Form.Item name="birthday" label="生日">
          {
            userInfo && type === 'detail' ? userInfo[0].birthday :
              <DatePicker />
          }
        </Form.Item>
        <Form.Item name="address" label="联系地址">
          {
            userInfo && type === 'detail' ? userInfo[0].address :
              <Input.TextArea rows={3} placeholder="请输入联系地址" />
          }
        </Form.Item>
        <Form.Item name="interest" label="爱好">
          {
            userInfo && type === 'detail' ? userInfo[0].interest :
              <Input type="text" placeholder="请输入爱好" />
          }
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default User